//
//  TalkViewController.m
//  TinyFortune
//
//  Created by lc on 16/5/21.
//  Copyright © 2016年 lc. All rights reserved.
//

#import "TalkViewController.h"
#import "TinyFortuneViewController.h"
#import "AVFile +  getDictionary.h"


//当行控制器长度
CGFloat const lenth = 67 ;


@interface TalkViewController ()<UITextViewDelegate>{
    UITextView *_textField;//发表的文字
    UIImageView *_imageView;//发表的图片
    NSDictionary *_dict;//用来返回用户头像的字典
}
@property (nonatomic,strong) NSMutableArray *objectIdArray;
@end

@implementation TalkViewController
#pragma mark - 懒加载
- (NSMutableArray *)objectIdArray{
    if (!_objectIdArray) {
        _objectIdArray = [NSMutableArray new];
    }
    return  _objectIdArray;
}
#pragma  mark - 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.navigationController setNavigationBarHidden:NO];
    [self createUI];
    

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark -createUI
- (void)createUI{
//导航栏设置
    UIBarButtonItem *left = [[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancel)];
    [self.navigationItem setLeftBarButtonItem:left];
    self.title = @"说说";
    UIBarButtonItem *right = [[UIBarButtonItem alloc]initWithTitle:@"发送" style:UIBarButtonItemStylePlain target:self action:@selector(message)];
    [self.navigationItem setRightBarButtonItem:right];
    //图片部分
    CGFloat margin =5 ;
    
    _imageView = [[UIImageView alloc]initWithFrame:CGRectMake(margin, margin + lenth, 70, 70)];
    _imageView.image = self.image;
    [self.view addSubview:_imageView];
    
    //编辑部分
    _textField = [[UITextView alloc]initWithFrame:CGRectMake(_imageView.frame.size.width + 2 *margin, margin + lenth, LC_WIDTH - _imageView.frame.size.width -2 * margin, _imageView.frame.size.height)];
    [self.view addSubview:_textField];
    
    //设置键盘类型
    [_textField setKeyboardType:UIKeyboardTypeDefault];
    //设置return按钮的样式
    [_textField setReturnKeyType:UIReturnKeyDone];

    _textField.text = @"分享一些新鲜事吧...";
   
    _textField.delegate = self ;
}
#pragma mark - textView协议方法实现
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    textView.text =@"";
    return YES;
}

#pragma mark - 按钮点击事件
- (void)cancel {
    //我是从A——>presentB-->push->c
    //这样写可以直接从c跳到A
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
   
}
//发送按钮的事件
- (void)message{
    
   AVUser *user = [AVUser currentUser];
    //没登陆的用户是不允许发表任何说说的
    if (!user) {
        UIAlertView *alert =[[UIAlertView alloc]initWithTitle:@"主人" message:@"登陆之后再发表说说好不咯" delegate:self cancelButtonTitle:@"取消" otherButtonTitles: nil];
        [alert show];
    }else{
    
    //讲jpeg文件转换成二进制的格式
    NSData *data = UIImageJPEGRepresentation(self.image, 0.01);
    AVFile *file = [AVFile fileWithData:data];
    NSDate *date = [NSDate new];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    formatter.dateFormat = @"MM-dd HH:mm";//MM月-DD日 HH时MM分
    NSString *timeString = [formatter stringFromDate:date];
    [file.metaData setObject:timeString forKey:@"time"];//时间
    [file.metaData setObject:_textField.text forKey:@"Description"];
   

    
    AVFile *iconFile = [user objectForKey:@"iconImage"] ;
    //防崩溃，因为如果键值不存在解析的话，会发生崩溃
    if (iconFile) {
        //获取头像信息字典
   _dict =  [AVFile fileWithDictionary:iconFile];
       
    }
    
    [file.metaData setObject:[user objectForKey:@"username"] forKey:@"name"];//名字
    [file.metaData setObject:_dict[@"url"] forKey:@"iconImage"];//头像
    [file.metaData setObject:user.mobilePhoneNumber forKey:@"username"];//电话号码唯一
    
        //提高用户交互的小菊花转
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        MBProgressHUD *hud = [MBProgressHUD HUDForView:self.view];
        hud.labelText = @"正在发送";
        
        
        //保存数据到服务器
    [file saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        if (succeeded) {
            [hud hide:YES];
            //设置广播内容
            NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
            //服务器表单中的objectID项目
            NSString *objectId = file.objectId;
            AVObject *idObject = [AVObject objectWithClassName:@"ID"];
            [idObject setObject:objectId forKey:@"ID"];
            [idObject save];
            NSDictionary *dict =[NSDictionary dictionaryWithObjectsAndKeys:objectId,@"objectId", nil];
            //将内容封装到广播中 给小幸运页面发送广播
            [nc postNotificationName:@"objectId" object:self userInfo:dict];
            
            [self.navigationController dismissViewControllerAnimated:YES completion:nil];        }
        else{
            NSLog(@"%@",error.localizedDescription);
        }
        
    }];
    }
}
@end
